<template>
  <section class="min-h-screen bg-white flex flex-col">

      <!-- 银行卡编辑弹窗 -->
    <div v-if="showBankCardEdit" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div class="bg-white rounded-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
        <!-- 弹窗头部 -->
        <div class="p-4 border-b border-gray-100">
          <div class="flex items-center justify-between">
            <div class="text-lg font-semibold text-gray-900">{{ isEditingCard ? '编辑银行卡' : '添加银行卡' }}</div>
            <button @click="closeBankCardEdit" class="text-gray-400 hover:text-gray-600">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-6 h-6">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
              </svg>
            </button>
          </div>
        </div>

        <!-- 弹窗内容 -->
        <div class="p-4 space-y-4">
          <!-- 银行卡号 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">银行卡号</label>
            <input
              v-model="editCardData.cardNumber"
              type="text"
              placeholder="请输入银行卡号"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @input="detectBankName"
            />
          </div>

          <!-- 银行名称（可手动输入） -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">银行名称</label>
            <input
              v-model="editCardData.bankName"
              type="text"
              placeholder="根据卡号自动识别"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <!-- 开户行 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">开户行</label>
            <input
              v-model="editCardData.bankBranch"
              type="text"
              placeholder="请输入开户行"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          <!-- 收款人 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">收款人</label>
            <input
              v-model="editCardData.accountName"
              type="text"
              placeholder="请输入收款人姓名"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>
        </div>

        <!-- 弹窗底部 -->
        <div class="p-4 border-t border-gray-100 flex gap-3">
          <button
            @click="closeBankCardEdit"
            class="flex-1 py-2.5 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            @click="saveBankCard"
            :disabled="!isEditFormValid"
            class="flex-1 py-2.5 bg-blue-500 text-white rounded-lg font-medium hover:bg-blue-600 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed"
          >
            保存
          </button>
        </div>
      </div>
    </div>

    <!-- 账户余额 -->
    <div class="bg-white p-4 border-b border-gray-100">
      <div class="text-sm text-gray-500">账户余额</div>
      <div class="text-2xl font-bold text-gray-900 mt-1">¥ {{ balance }}</div>
    </div>

    <!-- 提现金额输入 -->
    <div class="bg-white p-4 border-b border-gray-100">
      <div class="text-sm text-gray-500 mb-3">提现金额</div>
      <div class="flex items-center border-b-2 border-gray-200 pb-2">
        <span class="text-xl font-medium text-gray-700 mr-2">¥</span>
        <input
          v-model="amount"
          type="text"
          placeholder="0.00"
          class="flex-1 text-2xl font-medium text-gray-900 outline-none"
          @input="handleAmountInput"
        />
      </div>
      <div class="flex items-center justify-between mt-3">
        <div class="text-xs text-gray-400">可提现金额 ¥{{ balance }}</div>
        <button @click="amount = balance" class="text-xs text-blue-500 hover:text-blue-600">全部提现</button>
      </div>
    </div>

    <!-- 银行卡选择 -->
    <div class="bg-white p-4 border-b border-gray-100">
      <div class="text-sm text-gray-500 mb-3">到账银行卡</div>

      <!-- 银行卡显示 -->
      <div v-if="bankCard"
           @click="editBankCard"
           class="border-2 rounded-xl p-4 transition-all cursor-pointer border-blue-500 bg-blue-50">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-full flex items-center justify-center">
              <span class="text-white font-bold text-sm">{{ bankCard.bankName.charAt(0) }}</span>
            </div>
            <div>
              <div class="text-sm font-medium text-gray-900">{{ bankCard.bankName }}</div>
              <div class="text-xs text-gray-500 mt-1">尾号 {{ bankCard.cardNumber.slice(-4) }}</div>
              <div class="text-xs text-gray-500 mt-1">收款人: {{ bankCard.accountName }}</div>
            </div>
          </div>
          <div class="text-blue-500">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10"/>
            </svg>
          </div>
        </div>
      </div>

      <!-- 添加银行卡按钮 -->
      <div v-else
           @click="addBankCard"
           class="border-2 border-dashed border-gray-300 rounded-xl p-4 transition-all cursor-pointer hover:border-blue-500 hover:bg-blue-50">
        <div class="flex items-center justify-center gap-2 text-gray-500 hover:text-blue-500">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.5v15m7.5-7.5h-15"/>
          </svg>
          <span class="text-sm font-medium">请添加银行卡</span>
        </div>
      </div>

    </div>

    <!-- 提现说明 -->
    <div class="p-4">
      <div class="text-xs text-gray-500 space-y-1">
        <div>• 提现将在1-3个工作日内到账</div>
        <div>• 单笔提现金额最低10元</div>
        <div>• 每日提现次数上限为3次</div>
      </div>
    </div>

    <!-- 提交按钮 - 放在提现说明下方 -->
    <div class="p-4">
      <button
        @click="handleSubmit"
        :disabled="!isValid"
        class="w-full py-4 rounded-xl text-white font-medium text-lg transition-all shadow-lg"
        :class="isValid ? 'bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 active:scale-95' : 'bg-gray-300 cursor-not-allowed'">
        确认提现
      </button>
    </div>

    <!-- 优雅提示框 -->
    <transition
      enter-active-class="transition-opacity duration-300"
      enter-from-class="opacity-0"
      enter-to-class="opacity-100"
      leave-active-class="transition-opacity duration-200"
      leave-from-class="opacity-100"
      leave-to-class="opacity-0"
    >
      <div
        v-if="showAlert"
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
      >
        <!-- 背景遮罩层 - 只在错误时允许点击关闭 -->
        <div
          class="absolute inset-0 bg-black/30"
          @click="alertType === 'error' ? showAlert = false : null"
        ></div>

        <div class="relative bg-white rounded-2xl shadow-glass border border-gray-100 p-6 max-w-sm w-full mx-4">
          <!-- 图标 -->
          <div class="flex items-center justify-center w-12 h-12 mx-auto mb-4 rounded-full" :class="alertType === 'success' ? 'bg-green-50' : 'bg-red-50'">
            <svg v-if="alertType === 'success'" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-green-500">
              <path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clip-rule="evenodd" />
            </svg>
            <svg v-else xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-red-500">
              <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zm-1.72 6.97a.75.75 0 10-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 101.06 1.06L12 13.06l1.72 1.72a.75.75 0 101.06-1.06L13.06 12l1.72-1.72a.75.75 0 10-1.06-1.06L12 10.94l-1.72-1.72z" clip-rule="evenodd" />
            </svg>
          </div>

          <!-- 提示内容 -->
          <div class="text-center">
            <h3 class="text-lg font-semibold text-gray-900 mb-2">{{ alertType === 'success' ? '成功' : '提示' }}</h3>
            <p class="text-gray-600">{{ alertMessage }}</p>
          </div>

          <!-- 确认按钮 - 只在错误时显示 -->
          <div v-if="alertType === 'error'" class="mt-6">
            <button
              @click="showAlert = false"
              class="w-full py-2.5 text-white font-medium rounded-xl transition-colors bg-blue-500 hover:bg-blue-600"
            >
              确定
            </button>
          </div>
        </div>
      </div>
    </transition>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getBalance, modifyBankInfo, withdraw } from '../api/my'

const router = useRouter()
const route = useRoute()

// 优雅提示框状态
const showAlert = ref(false)
const alertMessage = ref('')
const alertType = ref('success') // 'success' 或 'error'

// 显示优雅提示框
const showAlertMessage = (message, type = 'success') => {
  alertMessage.value = message
  alertType.value = type
  showAlert.value = true

  // 只在成功时1.5秒后自动关闭
  if (type === 'success') {
    setTimeout(() => {
      showAlert.value = false
    }, 1500)
  }
  // 错误时不自动关闭，需要用户点击确认
}

// 账户余额
const balance = ref('0.00')
const loading = ref(false)

// 提现金额
const amount = ref('')

// 银行卡数据（从路由参数获取）
const bankCard = ref(null)

// 银行卡编辑相关状态
const showBankCardEdit = ref(false)
const isEditingCard = ref(false) // true: 编辑, false: 添加
const editCardData = ref({
  bankName: '',
  bankBranch: '',
  cardNumber: '',
  accountName: ''
})

// 加载银行信息数据
const loadBankInfo = () => {
  // 从路由参数获取数据
  const routeBalance = route.query.balance
  const routeHasBankInfo = route.query.hasBankInfo
  const routeBankInfo = route.query.bankInfo

  if (routeBalance) {
    balance.value = routeBalance
  }

  if (routeHasBankInfo === 'true' && routeBankInfo) {
    try {
      const bankInfo = JSON.parse(routeBankInfo)
      if (bankInfo && bankInfo.bankAccount) {
        // 格式化卡号用于显示
        const formattedCardNumber = bankInfo.bankAccount
          .replace(/\s/g, '')
          .replace(/(.{4})/g, '$1 ')
          .trim()
        
        bankCard.value = {
          id: Date.now(),
          bankName: bankInfo.bankName,
          bankBranch: bankInfo.openingBank,
          cardNumber: formattedCardNumber,
          accountName: bankInfo.recipient,
          cardType: '储蓄卡'
        }
        console.log('从路由参数加载银行卡信息:', bankCard.value)
      }
    } catch (error) {
      console.error('解析银行信息失败:', error)
    }
  }

  console.log('银行信息加载成功:', {
    balance: balance.value,
    hasBankInfo: !!bankCard.value,
    bankInfo: bankCard.value
  })
}

// 表单验证
const isValid = computed(() => {
  console.log('验证状态检查:', {
    amount: amount.value,
    balance: balance.value,
    bankCard: !!bankCard.value,
    bankCardValue: bankCard.value
  })
  
  // 先检查金额是否为空或无效
  if (!amount.value || amount.value.trim() === '') {
    console.log('金额为空，返回false')
    return false
  }
  
  const numAmount = parseFloat(amount.value)
  const numBalance = parseFloat(balance.value)
  
  // 检查金额是否有效 - 使用精度比较避免浮点数问题
  const isAmountValid = !isNaN(numAmount) && 
                       numAmount > 0 && 
                       numAmount <= numBalance && 
                       numAmount >= 0.01 - 0.000001  // 减去一个极小值避免精度问题
  
  // 检查银行卡信息
  const hasBankCard = !!bankCard.value
  
  console.log('验证结果:', {
    isAmountValid,
    hasBankCard,
    numAmount,
    numBalance
  })
  
  return isAmountValid && hasBankCard
})

// 编辑表单验证
const isEditFormValid = computed(() => {
  const card = editCardData.value
  return card.cardNumber.length >= 16 &&
         card.accountName.trim().length > 0 &&
         card.bankBranch.trim().length > 0 &&
         card.bankName.trim().length > 0
})

// 金额输入处理
const handleAmountInput = () => {
  const numAmount = parseFloat(amount.value)
  const numBalance = parseFloat(balance.value)
  if (numAmount > numBalance) {
    amount.value = balance.value
  }
}

// 银行卡号与银行名称的映射（绝对无冲突安全版）
const bankBinMap = {
  '621226': '中国工商银行',
  '622202': '中国工商银行',
  '95588': '中国工商银行',
  
  '622848': '中国农业银行',
  '622845': '中国农业银行',
  '95599': '中国农业银行',
  
  '622700': '中国建设银行',
  '622280': '中国建设银行',
  '622966': '中国建设银行',
  
  '601382': '中国银行',
  '621661': '中国银行',
  '621660': '中国银行',
  
  '622188': '中国邮政储蓄银行',
  '621098': '中国邮政储蓄银行',
  '621096': '中国邮政储蓄银行',
  
  '622666': '招商银行',
  '622575': '招商银行',
  '95555': '招商银行'
}

// 根据卡号识别银行名称
const detectBankName = () => {
  const cardNumber = editCardData.value.cardNumber.replace(/\s/g, '')

  // 查找匹配的银行BIN
  for (const [bin, bankName] of Object.entries(bankBinMap)) {
    if (cardNumber.startsWith(bin)) {
      editCardData.value.bankName = bankName
      return
    }
  }

  // 如果没有匹配到，清空银行名称
  if (cardNumber.length >= 6) {
    editCardData.value.bankName = '未知银行,请手动输入'
  } else {
    editCardData.value.bankName = ''
  }
}

// 打开银行卡编辑弹窗
const openBankCardEdit = (isEdit = false, cardData = null) => {
  isEditingCard.value = isEdit

  if (isEdit && cardData) {
    // 编辑模式：填充现有数据
    editCardData.value = { ...cardData }
  } else {
    // 添加模式：清空数据
    editCardData.value = {
      bankName: '',
      bankBranch: '',
      cardNumber: '',
      accountName: ''
    }
  }

  showBankCardEdit.value = true
}

// 关闭银行卡编辑弹窗
const closeBankCardEdit = () => {
  showBankCardEdit.value = false
  setTimeout(() => {
    editCardData.value = {
      bankName: '',
      bankBranch: '',
      cardNumber: '',
      accountName: ''
    }
  }, 300)
}

// 保存银行卡信息
const saveBankCard = async () => {
  if (!isEditFormValid.value) return

  try {
    // 准备要保存的数据，去除银行卡号中的空格
    // 注意：字段名必须与后端ModifyBankInfoParam类完全匹配
    const cardData = {
      bankName: editCardData.value.bankName,
      bankAccount: editCardData.value.cardNumber.replace(/\s/g, ''), // 去除空格
      openingBank: editCardData.value.bankBranch,
      recipient: editCardData.value.accountName
    }

    console.log('提交银行卡信息:', cardData)

    // 调用后端接口保存银行卡信息
    const result = await modifyBankInfo(cardData)

    if (result.success) {
      // 保存成功后，格式化卡号用于显示
      const formattedCardNumber = editCardData.value.cardNumber
        .replace(/\s/g, '')
        .replace(/(.{4})/g, '$1 ')
        .trim()

      // 更新前端银行卡数据
      bankCard.value = {
        ...editCardData.value,
        cardNumber: formattedCardNumber,
        id: isEditingCard.value ? bankCard.value.id : Date.now()
      }

      console.log('银行卡保存成功:', bankCard.value)

      // 显示成功提示
      showAlertMessage(result.message || '银行卡信息保存成功', 'success')

    } else {
      // 保存失败时显示错误信息
      showAlertMessage(result.message || '银行卡信息保存失败，请重试', 'error')
      return
    }

    closeBankCardEdit()

  } catch (error) {
    console.error('保存银行卡信息失败:', error)
    showAlertMessage('网络错误，请检查网络连接后重试', 'error')
  }
}

// 编辑银行卡
const editBankCard = () => {
  if (bankCard.value) {
    openBankCardEdit(true, bankCard.value)
  }
}

// 添加银行卡
const addBankCard = () => {
  openBankCardEdit(false)
}

// 提交提现申请
const handleSubmit = async () => {
  if (!isValid.value) return

  const numAmount = parseFloat(amount.value)
  
  // 显示加载状态
  loading.value = true

  try {
    console.log('提现申请提交:', {
      amount: numAmount,
      bankCard: bankCard.value,
      timestamp: new Date().toISOString()
    })

    // 调用后端API提交提现申请
    const result = await withdraw(numAmount)

    if (result.success) {
      showAlertMessage(result.message || `提现申请提交成功！\\n金额：¥${numAmount.toFixed(2)}\\n银行卡：${bankCard.value.bankName} 尾号${bankCard.value.cardNumber.slice(-4)}`, 'success')

      // 提现成功后的跳转
      setTimeout(() => {
        router.push('/mine')
      }, 2000)
    } else {
      showAlertMessage(result.message || '提现申请提交失败，请重试', 'error')
    }
  } catch (error) {
    console.error('提现申请失败:', error)
    showAlertMessage('网络错误，请检查网络连接后重试', 'error')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取银行信息
onMounted(() => {
  loadBankInfo()
})
</script>